package com.xkcyy.one.core.security;

import com.xkcyy.one.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        // String token = request.getHeader("Authorization");
        // if (token != null && token.startsWith("Bearer ")) {
        //     token = token.substring(7);
            
        //     // 根据token查询用户信息
        //     User user = userMapper.selectByToken(token);
        //     if (user != null) {
        //         // 创建身份凭证
        //         SysIdentity identity = new SysIdentity();
        //         identity.setUserId(user.getId());
        //         identity.setUsername(user.getUsername());
        //         identity.setToken(token);
        //         identity.setUser(user);
                
        //         // 设置当前身份凭证
        //         SysIdentity.setCurrent(identity);
        //         return true;
        //     }
                // 创建身份凭证
        SysIdentity identity = new SysIdentity();
        identity.setId(1L);
        identity.setName("demo");
        identity.setCode("demo");
        identity.setToken("demo");
        
        // 设置当前身份凭证
        SysIdentity.setCurrent(identity);
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求完成后清除身份凭证
        SysIdentity.clear();
    }
} 